var app = getApp();
var common_Js = require("../../component/common.js"), fetchApi = require("../../utils/httpPost.js")
import Toast from '../../component/vant/toast/toast';
import Dialog from '../../component/vant/dialog/dialog';
import Notify from '../../component/vant/notify/notify';
const CryptoJS = require("../../utils/aesUtil.js")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgurl:app.getImgUrl(),
    userInfo: {},
    hasUserInfo: false,
    current: 0,
    pageIndex: 1,
    pageSize: 10,
    tabs: [],//标题tab菜单
    loading: false,
    netWork: true,
    isLoading: true,
    showGoAuth:true,
    hotword:'请输入商品名称',
    isLogin:0,
    autoplay:true,
    wd:0,
    jd:0,
    banners:[],
    menus:[],
    notices:[],
    sections: [],//内容行集合
    is_show_search:0,
    ag_id:0,//邀请人id
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    specialMenuRowCount:2,
    propertyMenuRowCount:5,
    normalMenuRowCount:5,
    rowCount:5,
    newUserMenuRowCount:4,
    first_page_filter_css:'',
    action:'',
    currentTab: 0,
    tabList:[],
    productList:[],
    typeId:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // var o = getCurrentPages().pop();
    console.log('onLoad options',options)
    if (options!=undefined && options.q) {
      var q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
      q = "?" + q.split("?")[1];
      this.data.query = q;
      console.log('q', q)
      options = common_Js.getQueryVariable(q);
    }
    
    var isLogin = app.getStorageSync("isLogin");
    console.log('onLoad isLogin', isLogin)
    app.setStorageSync("ag_id",0);
    if(options!=undefined && options.ag_id){
      this.data.ag_id = parseInt(options.ag_id);
      app.setStorageSync("ag_id",this.data.ag_id);
    }
    
    this.data.jd = app.getStorageSync("lng")!=undefined && app.getStorageSync("lng")!='' ?app.getStorageSync("lng") : 0;
    this.data.wd = app.getStorageSync("lat")!=undefined && app.getStorageSync("lat")!='' ?app.getStorageSync("lat") : 0;

    // this.onHttpInit();
    
    wx.getPrivacySetting({
      success: res => {
        console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
        } else {
        }
      },
      fail: () => {},
      complete: () => {}
    })
    this.modalcnt()
  },
  onShow: function () {
    var that = this;
    that.data.pageIndex = 1;
    var isLogin = app.getStorageSync('isLogin');
    console.log('onShow isLogin', isLogin)
    // that.setData({ isLogin: isLogin})
    if(isLogin == 1){
      var user_id = app.getStorageSync('user_id');
      if(user_id > 0){
        app.getUserInfoById(user_id)
      }else{
        wx.navigateTo({
          url: '/pages/login/index',
        })
      }
    }
    //自定义的tabbar
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,
      })
    }
  },
  modalcnt:function  ()  {
    var that = this;
    console.log('modalcnt ====== ')
    //获取经纬度  
    wx.getLocation({
      type:  'gcj02',
      success:  function  (res)  {
        console.log('modalcnt ====== ', res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.data.wd = latitude//纬度
        that.data.jd = longitude//经度
        that.setData({
          wd : latitude,
          jd : longitude
        })
        app.setStorageSync("lng",longitude);
        app.setStorageSync("lat",latitude);
        that.onHttpInit();
      },fail:function(res){
        that.data.wd = 0
        that.data.jd = 0
        app.setStorageSync("lng",0);
        app.setStorageSync("lat",0);
        that.onHttpInit()
      }
    })
  },
  handleChange({ detail }) {
    console.log('detail',detail)
    this.data.pageIndex = 1;
    this.data.typeId = this.data.tabList[detail.index].id;
    this.data.productList = []
    this.setData({
      productList : [],
      currentTab: detail.index
    })
    this.onHttpProductList(this.data.typeId);
  },
  goSearch(res){
    console.log('goSearch')
    wx.navigateTo({
      url: '/pagesMer/pages/search/search',
    })
  },
  goNotice(res){
    console.log('goNotice',res)
    var id = res.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/notice/detail/index?id='+ id,
    })
  },
  goShowBuild(){
    Toast('工程师正加紧建设中...');
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/index/index/bingge', {
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex,
      longitude: that.data.jd,
      latitude: that.data.wd,
    }, function (res) {
      console.log('首页数据',res)
      if (res.data.code == 0) {
        that.data.pageIndex = that.data.pageIndex + 1;
        that.data.typeId = res.data.data.typeList[0].id;     
        that.setData({
            banners:res.data.data.banners,
            tabList: res.data.data.typeList,
            productList: res.data.data.products,
            menus: res.data.data.menuList,
            sections: res.data.data.sections,
            notices: res.data.data.notices,
            is_show_search:res.data.data.is_show_search,
            specialMenuRowCount: res.data.data.specialMenuRowCount,
            propertyMenuRowCount:res.data.data.propertyMenuRowCount,
            normalMenuRowCount:res.data.data.normalMenuRowCount,
            rowCount:res.data.data.rowCount,
            newUserMenuRowCount: res.data.data.newUserMenuRowCount,
            first_page_filter_css: res.data.data.first_page_filter_css,
        })
        that.setData({
          isLoading: false, loading: true, netWork: true,
        });
      } else {
        that.setData({ isLoading: false, loading: true, netWork: true })
      }
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, function () {
        that.setData({  isLoading: false,  loading: true,  netWork: true, }) 
    })
  },
  pushToDetail: function (e) {
    console.log("pushToDetail.e", e)
    var itemData = e.detail.target.dataset.item;
    console.log("itemData", itemData)
    // 链接的类型 0 - 单商品id 1 - 商品页（title_menu_id）2 - 团购商品id 3 - 团购商品页id  4 - 优惠券id
    console.log("itemData.linkType", itemData.linkType)
    if (itemData.linkType == 'product') {//
      wx.navigateTo({
        url: '/pages/product/detail/index?id=' + itemData.linkId + '&from=appHome'
      });
    }
  },
  goSearch(){
    wx.navigateTo({
      url: '/pagesMer/pages/search/search',
    })
  },
  onSearch(val){
    console.log('onSearch',val)
    this.data.keyword = val.detail;
    this.onHttpInit()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作  下拉刷新
   */
  onPullDownRefresh: function () {
    this.data.pageIndex = 1
    this.setData({
      loading: false,
      netWork: false,
      isLoading: true
    })
    this.onHttpInit()
  },
  /**
   * 页面上拉触底事件的处理函数    加载更多
   */
  onReachBottom: function () {
    this.onHttpProductList(this.data.typeId);
  },
  /**
   * 获取页面数据的 http请求
    a.httpPost('/titleMenu/list', {
   */
  onHttpProductList: function (type_id) {
    var that = this;
    fetchApi.httpPost('/product/type/product/list/bg',{
      cateId: type_id,
      pageIndex: that.data.pageIndex,
      pageSize: that.data.pageSize,
    }, function (res) {
      console.log("加载更多数据", res)
      if(res.data.totalcount > 0){
        that.data.pageIndex = that.data.pageIndex + 1;
        var productList = res.data.data.products;
        for (var index in productList) {
          that.data.productList.splice(that.data.productList.length, 0, productList[index]);
        }
        that.setData({ productList: that.data.productList });
      }
      that.setData({ isLoading: false, loading: true, netWork: true })
      // complete
      wx.stopPullDownRefresh(); //停止下拉刷新
    },function(){})
  },
  scanCode: function (res) {
    console.log('scanCode res',res)
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    that.data.from_page = 'scancode'
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      wx.scanCode({
        success: (res) => {
          console.log("扫码结果", res);
          var qrcontent = res.result;
          console.log('扫码结果',qrcontent)
          var json_param = {}
          if(qrcontent.indexOf('https://') >= 0){
            var q = "?" + qrcontent.split("?")[1];
            var json_param = common_Js.getQueryVariable(q);
            if(qrcontent.indexOf('shop/getEgg') >= 0){
              wx.navigateTo({ url: '/pagesMer/pages/payEgg/index?no=' + json_param.no})
            } else if(qrcontent.indexOf('produ/detail') >= 0){//商品详情界面
              wx.navigateTo({
                url: '/pages/product/detail/index?id=' + json_param.id,
              })
            } else if(qrcontent.indexOf('ordercoupon/qr') >= 0){//核销界面
              console.log('ordercoupon')
              that.couponVerifyOp(json_param.id)
            } else if(qrcontent.indexOf('merEgg/product') >= 0){//商家商品列表界面
              wx.navigateTo({
                url: '/pages/product/list/index?no=' + json_param.no,
              })
            } else if(qrcontent.indexOf('promotionBg/qr') >= 0){//推广代理页面
              wx.navigateTo({
                url: '/pages/ag/index?ag_id=' + json_param.prag_id,
              })
            }  else if(qrcontent.indexOf('coupon/store') >= 0){//通过销售卡库二维码获取卡券
              wx.navigateTo({
                url: '/pagesMer/pages/couponStore/add/index?id=' + json_param.id,
              })
            } else {
              Toast.fail("当前二维码无效");
            }
          }
        },
        fail: (res) => { console.log(res); }
      })
    }
  },
  couponVerifyOp:function(coupon_qr_id){
    fetchApi.httpPost('/product/order/coupon/qr/detail', {
      coupon_qr_id: coupon_qr_id,
    }, function (res) {
      console.log("卡券核销二维码详情", res)
      if (res.data.code == 0) {
        let is_can_verify = res.data.data.is_can_verify;
        if(is_can_verify == 1){
          wx.navigateTo({
            url: '/pagesMer/pages/orderCoupon/verify/index?id=' + coupon_qr_id,
          })
        }else{
          Toast.fail('您没有该权限');
        }
      } else {
        Toast.fail(res.data.msg);
      }
    }, function () { })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var user_id = app.getStorageSync("user_id");
    console.log("转发成功 user_id",user_id)
    return {
      title: "",
      path: '/pages/home/home?ag_id='+user_id,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  },  
})